<template>
  <div class="account-settings">
    <div class="settings-header">
      <h1>账号设置</h1>
    </div>

    <div class="settings-container">
      <!-- 安全设置 -->
      <div class="settings-section" v-if="user">
        <h2 class="section-title">安全设置</h2>
        
        <!-- 手机号设置 -->
        <div class="settings-item" @click="showPhoneDialog = true">
          <div class="item-content">
            <span class="item-label">安全手机:</span>
            <span class="item-value">{{ formatPhone(user.phone) }}</span>
          </div>
          <span class="item-status">{{ user.phone ? '已绑定' : '未绑定' }}</span>
        </div>
        
        <!-- 邮箱设置 -->
        <div class="settings-item" @click="showEmailDialog = true">
          <div class="item-content">
            <span class="item-label">安全邮箱:</span>
            <span class="item-value">{{ formatEmail(user.email) }}</span>
          </div>
          <span class="item-status">{{ user.email ? '已绑定' : '未绑定' }}</span>
        </div>
        
        <!-- 密码设置 -->
        <div class="settings-item" @click="showPasswordDialog = true">
          <div class="item-content">
            <span class="item-label">登录密码</span>
            <span class="item-value">********</span>
          </div>
          <span class="item-status">修改</span>
        </div>
        
        <!-- 第三方账号 -->
        <div class="settings-item">
          <div class="item-content">
            <span class="item-label">第三方账号</span>
            <span class="item-value">未绑定</span>
          </div>
          <span class="item-status">管理</span>
        </div>
      </div>
    </div>

    <!-- 修改手机号弹窗 -->
    <div v-if="showPhoneDialog" class="modal-overlay">
      <div class="modal">
        <div class="modal-header">
          <h3>修改手机号</h3>
          <button @click="showPhoneDialog = false" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="updatePhone">
            <div class="form-group">
              <label>旧手机号</label>
              <input 
                v-model="phoneForm.oldPhone" 
                type="text" 
                placeholder="请输入旧手机号"
                required
              />
              <small class="error-message" v-if="phoneForm.oldPhone && !phonePattern.test(phoneForm.oldPhone)">
                手机号格式不正确
              </small>
            </div>
            <div class="form-group">
              <label>新手机号</label>
              <input 
                v-model="phoneForm.newPhone" 
                type="text" 
                placeholder="请输入新手机号"
                required
              />
              <small class="error-message" v-if="phoneForm.newPhone && !phonePattern.test(phoneForm.newPhone)">
                手机号格式不正确
              </small>
            </div>
            <div class="modal-footer">
              <button type="button" @click="showPhoneDialog = false" class="cancel-btn">取消</button>
              <button type="submit" class="confirm-btn" :disabled="isUpdatingPhone">
                {{ isUpdatingPhone ? '处理中...' : '确认' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 修改邮箱弹窗 -->
    <div v-if="showEmailDialog" class="modal-overlay">
      <div class="modal">
        <div class="modal-header">
          <h3>修改邮箱</h3>
          <button @click="showEmailDialog = false" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="updateEmail">
            <div class="form-group">
              <label>旧邮箱</label>
              <input 
                v-model="emailForm.oldEmail" 
                type="email" 
                placeholder="请输入旧邮箱"
                required
              />
              <small class="error-message" v-if="emailForm.oldEmail && !emailPattern.test(emailForm.oldEmail)">
                邮箱格式不正确
              </small>
            </div>
            <div class="form-group">
              <label>新邮箱</label>
              <input 
                v-model="emailForm.newEmail" 
                type="email" 
                placeholder="请输入新邮箱"
                required
              />
              <small class="error-message" v-if="emailForm.newEmail && !emailPattern.test(emailForm.newEmail)">
                邮箱格式不正确
              </small>
            </div>
            <div class="modal-footer">
              <button type="button" @click="showEmailDialog = false" class="cancel-btn">取消</button>
              <button type="submit" class="confirm-btn" :disabled="isUpdatingEmail">
                {{ isUpdatingEmail ? '处理中...' : '确认' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <!-- 修改密码弹窗 -->
    <div v-if="showPasswordDialog" class="modal-overlay">
      <div class="modal">
        <div class="modal-header">
          <h3>修改密码</h3>
          <button @click="showPasswordDialog = false" class="close-btn">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="updatePassword">
            <div class="form-group">
              <label>旧密码</label>
              <input 
                v-model="passwordForm.oldPassword" 
                type="password" 
                placeholder="请输入旧密码"
                required
              />
            </div>
            <div class="form-group">
              <label>新密码</label>
              <input 
                v-model="passwordForm.newPassword" 
                type="password" 
                placeholder="请输入新密码"
                required
              />
              <small class="error-message" v-if="passwordForm.newPassword && !passwordPattern.test(passwordForm.newPassword)">
                8-16位，含大小写字母和数字
              </small>
            </div>
            <div class="form-group">
              <label>确认密码</label>
              <input 
                v-model="passwordForm.confirmPassword" 
                type="password" 
                placeholder="请再次输入新密码"
                required
              />
              <small class="error-message" v-if="passwordForm.confirmPassword && passwordForm.newPassword !== passwordForm.confirmPassword">
                两次密码不一致
              </small>
            </div>
            <div class="modal-footer">
              <button type="button" @click="showPasswordDialog = false" class="cancel-btn">取消</button>
              <button type="submit" class="confirm-btn" :disabled="isUpdatingPassword">
                {{ isUpdatingPassword ? '处理中...' : '确认' }}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from '../api/axios';
import { useRouter } from 'vue-router';

const router = useRouter();
const user = ref(null);

// 弹窗控制
const showPhoneDialog = ref(false);
const showEmailDialog = ref(false);
const showPasswordDialog = ref(false);

// 加载状态
const isUpdatingPhone = ref(false);
const isUpdatingEmail = ref(false);
const isUpdatingPassword = ref(false);

// 表单数据
const phoneForm = ref({
  oldPhone: '',
  newPhone: ''
});
const emailForm = ref({
  oldEmail: '',
  newEmail: ''
});
const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
});

// 验证规则
const phonePattern = /^1[3-9]\d{9}$/;
const emailPattern = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
const passwordPattern = /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[^]{8,16}$/;

// 格式化显示
const formatPhone = (phone) => {
  return phone ? phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2') : '未绑定';
};

const formatEmail = (email) => {
  if (!email) return '未绑定';
  const [name, domain] = email.split('@');
  const hiddenName = name.length > 2 
    ? name.substring(0, 2) + '*'.repeat(name.length - 2)
    : '*'.repeat(name.length);
  return `${hiddenName}@${domain}`;
};

// 更新操作
const updatePhone = async () => {
  if (!validatePhone()) return;
  if (phoneForm.value.oldPhone !== user.value.phone) {
    alert('旧手机号不正确');
    return;
  }

  isUpdatingPhone.value = true;
  try {
    const response = await axios.post('/api/users/updatephone', {
      phone: phoneForm.value.newPhone,
      userid: user.value.id,
      oldphone: phoneForm.value.oldPhone
    });
    
    if (response.data.code === 200) {
      user.value.phone = phoneForm.value.newPhone;
      showPhoneDialog.value = false;
      phoneForm.value = { oldPhone: '', newPhone: '' };
      updateSessionStorage('phone', user.value.phone);
      alert('手机号修改成功');
    } else {
      alert(response.data.msg || '修改手机号失败');
    }
  } catch (error) {
    console.error('修改手机号出错:', error);
    alert('修改手机号时发生错误');
  } finally {
    isUpdatingPhone.value = false;
  }
};

const updateEmail = async () => {
  if (!validateEmail()) return;

  if (emailForm.value.oldEmail !== user.value.email) {
    alert('旧邮箱不正确');
    return;
  }

  isUpdatingEmail.value = true;
  try {
    const response = await axios.post('/api/users/updateemail', {
      email: emailForm.value.newEmail,
      userid: user.value.id,
      oldemail: emailForm.value.oldEmail
    });
    
    if (response.data.code === 200) {
      user.value.email = emailForm.value.newEmail;
      showEmailDialog.value = false;
      emailForm.value = { oldEmail: '', newEmail: '' };
      updateSessionStorage('email', user.value.email);
      alert('邮箱修改成功');
    } else {
      alert(response.data.msg || '修改邮箱失败');
    }
  } catch (error) {
    console.error('修改邮箱出错:', error);
    alert('修改邮箱时发生错误');
  } finally {
    isUpdatingEmail.value = false;
  }
};

const updatePassword = async () => {
  if (!validatePassword()) return;
  if(passwordForm.value.oldPassword !== user.value.pwd){
    alert('旧密码不正确');
    return;
  }
  
  isUpdatingPassword.value = true;
  try {
    const response = await axios.post('/api/users/updatepwd', {
      pwd: passwordForm.value.newPassword,
      userid: user.value.id,
      oldpwd: passwordForm.value.oldPassword
    });
    
    if (response.data.code === 200) {
      showPasswordDialog.value = false;
      passwordForm.value = { oldPassword: '', newPassword: '', confirmPassword: '' };
      alert('密码修改成功，请重新登录');
      
      // 清除用户会话数据
      sessionStorage.removeItem('user');
      sessionStorage.removeItem('token');
      
      // 跳转到登录页
      router.push('/login'); 
    } else {
      alert(response.data.msg || '修改密码失败');
    }
  } catch (error) {
    console.error('修改密码出错:', error);
    alert('修改密码时发生错误');
  } finally {
    isUpdatingPassword.value = false;
  }
};

// 验证函数
const validatePhone = () => {
  if (!phonePattern.test(phoneForm.value.oldPhone)) {
    alert('请输入正确的旧手机号');
    return false;
  }
  if (!phonePattern.test(phoneForm.value.newPhone)) {
    alert('请输入正确的新手机号');
    return false;
  }
  if (phoneForm.value.oldPhone === phoneForm.value.newPhone) {
    alert('新手机号不能与旧手机号相同');
    return false;
  }
  return true;
};

const validateEmail = () => {
  if (!emailPattern.test(emailForm.value.oldEmail)) {
    alert('请输入正确的旧邮箱');
    return false;
  }
  if (!emailPattern.test(emailForm.value.newEmail)) {
    alert('请输入正确的新邮箱');
    return false;
  }
  if (emailForm.value.oldEmail === emailForm.value.newEmail) {
    alert('新邮箱不能与旧邮箱相同');
    return false;
  }
  return true;
};

const validatePassword = () => {
  if (!passwordPattern.test(passwordForm.value.newPassword)) {
    alert('新密码必须8-16位，包含大小写字母和数字');
    return false;
  }
  if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
    alert('两次输入的密码不一致');
    return false;
  }
  return true;
};

// 更新sessionStorage中的用户数据
const updateSessionStorage = (key, value) => {
  const userData = JSON.parse(sessionStorage.getItem('user'));
  if (userData) {
    userData[key] = value;
    sessionStorage.setItem('user', JSON.stringify(userData));
  }
};

// 加载用户数据
const loadUserData = () => {
  const userData = JSON.parse(sessionStorage.getItem('user'));
  if (userData) {
    user.value = {
      id: userData.userid || userData.id,
      phone: userData.phone || '',
      email: userData.email || '',
      pwd: userData.pwd || ''
    };
    console.log(userData)
  }
};

onMounted(() => {
  loadUserData();
});
</script>

<style scoped>
.account-settings {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.settings-header {
  margin-bottom: 24px;
}

.settings-header h1 {
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.settings-container {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.settings-section {
  padding: 16px;
}

.section-title {
  font-size: 16px;
  color: #666;
  margin-bottom: 16px;
  font-weight: 500;
}

.settings-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
}

.settings-item:last-child {
  border-bottom: none;
}

.item-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.item-label {
  font-size: 15px;
  color: #333;
}

.item-value {
  font-size: 14px;
  color: #666;
}

.item-status {
  font-size: 14px;
  color: #1989fa;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #333;
}

.form-group input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
  
  &:focus {
    border-color: #ff6700;
  }
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
  display: block;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 400px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

.modal-header {
  padding: 16px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.modal-body {
  padding: 16px;
  max-height: 70vh;
  overflow-y: auto;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding-top: 16px;
  border-top: 1px solid #eee;
}

.cancel-btn, .confirm-btn {
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.cancel-btn {
  background-color: #f5f5f5;
  border: 1px solid #ddd;
  color: #333;
}

.confirm-btn {
  background-color: #1989fa;
  border: 1px solid #1989fa;
  color: white;
}

.confirm-btn:disabled {
  background-color: #cccccc;
  border-color: #cccccc;
  cursor: not-allowed;
}
</style>